import { Injectable } from '@nestjs/common';
import { RuntimeException } from 'src/exceptions/runtime.exception';
import { RegisterDto } from '../auth/dtos/register.dto';
import { LoginDto } from '../auth/dtos/login.dto';
import { UserService } from 'src/user/user.service';
import { compare } from 'bcrypt';
import { JWT } from 'src/constants';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class AuthService {
  constructor(
    private userService: UserService,
    private jwtService: JwtService,
  ) {}

  async login({ username, password }: LoginDto) {
    const user = await this.userService.findOne({ username });
    if (user === null) {
      throw new RuntimeException('用户不存在');
    }
    const verify = await compare(password, user?.password);
    if (!verify) {
      throw new RuntimeException('密码错误');
    }
    const payload: UserPayload = {
      sub: user.id,
      username: user.username,
      root: username === JWT.rootUser,
    };
    return { token: await this.jwtService.signAsync(payload) };
  }

  async register({ username, password, mobile, email, type }: RegisterDto) {
    const user = await this.userService.findOne({ username });
    if (user !== null) {
      throw new RuntimeException('用户已存在');
    }
    return await this.userService.create({
      username,
      password,
      mobile,
      email,
      type,
    });
  }
}
